﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Globalization;

using CommunergyLogic;
using System.Collections.Generic;
using System.Data.SqlClient;
using Communergy.Repository;
using Communergy.Repository.EntityFramework;

public partial class EnergyEntry_electricity : System.Web.UI.Page
{
    ElectricityMeter meter;
    int meterId;
    communergyEntities db = new communergyEntities();
    List<ElectricityDaily_ManualReading> oldReadings = new List<ElectricityDaily_ManualReading>();

    protected void Page_Load(object sender, EventArgs e)
    {
        vldDateCurrent.ValueToCompare = DateTime.Today.ToShortDateString();
        vldReadingValid.ErrorMessage = "New reading must be bigger than the last one";
        //vldDateCurrent.MinimumValue = DateTime.MinValue.ToShortDateString();
        //vldDateCurrent.MaximumValue = DateTime.Today.ToShortDateString();
        //vldReadingValid.MaximumValue = int.MaxValue.ToString();


        var meterIdString = Request.QueryString["meterId"];
        meter = Helpers.GetMeterIfBelongsToUser(db, meterIdString);
        if (meter != null)
        {
            meter.ElectricityDaily_Manual.Load();
            meter.ElectricityDaily_ManualReading.Load();
            meterId = meter.me_id;
            if (!Page.IsPostBack)
            {
                lblMeterInfo.Text = string.Format("Enter reading for meter {0}", meter.me_meterName);
                UpdateElectricity();
            }
            meter.ElectricityDaily_ManualReading.Load();
            BuildReadingsList();

        }
    }

    private void BuildReadingsList()
    {
        oldReadings = meter.ElectricityDaily_ManualReading.OrderByDescending(rg => rg.mr_dateTime).ToList();
        gridPastReadings.DataSource = oldReadings;
        gridPastReadings.DataBind();
        panelPreviousReadings.Visible = oldReadings.Count > 0;
    }

    //get last electricity reading and print on form
    private void UpdateElectricity()
    {
        newReadingChart.Visible = false;
        var electricity = meter.ElectricityDaily_ManualReading.OrderByDescending(de => de.mr_dateTime);
        DateTime dtmElectricity;
        decimal electricityReading;
        if (electricity.Count() > 0)
        {
            var firstElectricity = electricity.Take(1).FirstOrDefault();
            dtmElectricity = firstElectricity.mr_dateTime.AddDays(1);
            electricityReading = firstElectricity.mr_reading;

            lblInstructions.Text = string.Format("Please enter a new reading for {0} or later", dtmElectricity.ToShortDateString());
            
        }
        else
        {
            dtmElectricity = DateTime.Now.Date;
            electricityReading = 0;
            lblInstructions.Text = string.Format("Please enter the first reading for {0}", meter.me_meterName);
        }
        txtElectricityDate.Text = dtmElectricity.ToString(CultureInfo.CreateSpecificCulture("en-GB").DateTimeFormat.ShortDatePattern);
        txtElectricityReading.Text = electricityReading.ToString();
        vldReadingValid.ValueToCompare = electricityReading.ToString();
        vldReadingValid.ErrorMessage = string.Format("ReadingTotal must be greater than {0}", electricityReading);

    }

    protected void btnSubmitElectricity_Click(object sender, EventArgs e)
    {
        panelEntry.Visible = false;
        DateTime dtReadingDate = DateTime.Parse(txtElectricityDate.Text, CultureInfo.CreateSpecificCulture("en-GB").DateTimeFormat);
        decimal electricityReading = decimal.Parse(txtElectricityReading.Text);

        var oldReadingsSeries = newReadingChart.Series["oldReadingsSeries"];
        oldReadingsSeries.Points.Clear();


        //from specified data, calculate new readings
        var firstElectricity = ManualDataHelper.GetMostRecentElectricity_ManualReadingForMeter(meterId);
        var newReadings = ManualDataHelper.CreateElectricityReadings(firstElectricity, dtReadingDate, electricityReading, meterId);

        //get old readings, if appropriate
        if (firstElectricity != null)
        {
            var dateFrom = firstElectricity.de_dateTime.AddDays(-10);
            var oldReadings = ManualDataHelper.GetPastElectricity_ManualReadingForMeter(meterId, dateFrom);


            foreach (var reading in oldReadings)
            {
                var convertedReading = Convert.ToDouble(reading.de_kWhDaily.Value);
                oldReadingsSeries.Points.AddXY(reading.de_dateTime, convertedReading);
            }


            var newReadingsSeries = newReadingChart.Series["newReadingsSeries"];
            newReadingsSeries.Points.Clear();
            foreach (var reading in newReadings)
            {
                var convertedReading = Convert.ToDouble(reading.de_kWhDaily.Value);
                newReadingsSeries.Points.AddXY(reading.de_dateTime, convertedReading);
            }

            newReadingChart.Visible = true;
            lblElectricityInfo.Text = string.Format("Add {0} records, from {1} to {2}, average value {3:0.00} kWh?", newReadings.Count, newReadings.First().de_dateTime.ToLongDateString(), newReadings.Last().de_dateTime.ToLongDateString(), newReadings.First().de_kWhDaily);

        }
        else
        {
            lblElectricityInfo.Text = string.Format("Add the first record for {0}, {1:0.00} kWh on {2}?", meter.me_meterName, newReadings.First().de_kWhDaily, newReadings.First().de_dateTime.ToLongDateString());
            newReadingChart.Visible = false;
        }
        btnConfirmElectricity.Visible = true;
        btnCancelElectricity.Visible = true;
        btnSubmitElectricity.Visible = false;

    }
    protected void btnConfirmElectricity_Click(object sender, EventArgs e)
    {
        DateTime dtReadingDate = DateTime.Parse(txtElectricityDate.Text, CultureInfo.CreateSpecificCulture("en-GB").DateTimeFormat);
        decimal electricityReading = decimal.Parse(txtElectricityReading.Text);


        var firstElectricity = ManualDataHelper.GetMostRecentElectricity_ManualReadingForMeter(meterId);
        meter.ElectricityDaily_ManualReading.Add ( new ElectricityDaily_ManualReading{ mr_dateTime = dtReadingDate, mr_reading = electricityReading});
        var newReadings = ManualDataHelper.CreateElectricityReadings(firstElectricity , dtReadingDate, electricityReading, meterId);
        ManualDataHelper.SaveNewElectricityReadings(db, meter, newReadings);

        lblElectricityInfo.Text = string.Format("Added {0} records, from {1} to {2}, average value {3:00} kWh", newReadings.Count, newReadings.First().de_dateTime.ToLongDateString(), newReadings.Last().de_dateTime.ToLongDateString(), newReadings.First().de_kWhDaily);


        UpdateElectricity();
        BuildReadingsList();
        btnConfirmElectricity.Visible = false;
        btnCancelElectricity.Visible = false;
        btnSubmitElectricity.Visible = true;
        panelEntry.Visible = true;
    }
    protected void btnCancelElectricity_Click(object sender, EventArgs e)
    {
        newReadingChart.Visible = false;
        lblElectricityInfo.Text = "New reading entry cancelled";
        btnConfirmElectricity.Visible = false;
        btnCancelElectricity.Visible = false;
        btnSubmitElectricity.Visible = true;
        
        panelEntry.Visible = true;
    }

    protected void gridPastReadings_SelectedIndexChanged(object sender, EventArgs e)
    {

    }

    protected void gridPastReadings_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        var cmdArg = e.CommandArgument;
        string cmdName = e.CommandName.ToString();
        var cmdSource = e.CommandSource;
        var readingId = Convert.ToInt32(cmdArg);
        var editReading = oldReadings.Where(r => r.mr_id == readingId).FirstOrDefault();
        if (editReading != null)
        {
            switch (cmdName)
            {
                case "Edit":

                    txtElectricityDate.Text = editReading.mr_dateTime.ToString(CultureInfo.CreateSpecificCulture("en-GB").DateTimeFormat.ShortDatePattern);
                    txtElectricityReading.Text = editReading.mr_reading.ToString("0.0");
                    break;
                case "Delete":
                    meter.ElectricityDaily_ManualReading.Remove(editReading);
                    db.DeleteObject(editReading);
                    db.SaveChanges();
                    RebuildElectricityFromReadings();
                    BuildReadingsList();
                    UpdateElectricity();
                    lblElectricityInfo.Text = string.Format("Deleted the reading of {0} on {1}", editReading.mr_reading, editReading.mr_dateTime.ToShortDateString());
                    break;
                default:
                    break;
            }
        }
    }

    protected void gridPastReadings_RowEditing(object sender, GridViewEditEventArgs e)
    {

    }

    private void RebuildElectricityFromReadings()
    {
        SqlConnection conn = new SqlConnection();
        conn.ConnectionString = ConfigurationManager.ConnectionStrings["CommunergyConnectionString"].ConnectionString;
        conn.Open();
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = conn;
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandText = "Delete_ElectricityDaily_Manual_ByMeterId";

        SqlParameter prmMeterId = new SqlParameter();
        prmMeterId.ParameterName = "@MeterId";
        prmMeterId.SqlDbType = SqlDbType.Float;
        prmMeterId.Value = meterId;

        cmd.Parameters.Add(prmMeterId);

        cmd.ExecuteNonQuery();
        List<ElectricityDaily_Manual> newReadings = new List<ElectricityDaily_Manual>();
        var existingManualReadings = meter.ElectricityDaily_ManualReading.OrderBy(rg => rg.mr_dateTime);
        ElectricityDaily_Manual firstElectricity = null;
        foreach (var manualReading in existingManualReadings)
        {
            var theseReadings = ManualDataHelper.CreateElectricityReadings(firstElectricity, manualReading.mr_dateTime, manualReading.mr_reading, meterId);
            newReadings = newReadings.Union(theseReadings).ToList();
            firstElectricity = theseReadings.Last();
        }
        ManualDataHelper.SaveNewElectricityReadings(db, meter, newReadings);

    }

    protected void gridPastReadings_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {

    }



}
